﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Customer.Bussiness_Service;
using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ServiceCore;
using ServiceCore.Tool;
using ServiceCore.Tool.AliFace;
using ServiceCore.Tool.Barcode;
using ServiceCore.Tool.ES;
using ServiceCore.Tool.MiniProgram;
using ServiceCore.Tool.Mqtt;
using ServiceCore.Tool.NPOI;
using ServiceCore.Tool.Post;
using ServiceCore.Tool.TIM;
using ServiceCore.Tool.TIM.chat_message;
using ServiceCore.Tool.TIM.im_open_login_svc;
using ServiceCore.Tool.Wx.customservice;
using ServiceCore.Tool.Wx.diy_menu;
using ServiceCore.Tool.Wx.media;
using static ServiceCore.Tool.Analyzer_jieba;
using static ServiceCore.Tool.ES.Es_knowledge;

namespace Customer.Controllers
{
    [ApiController, Route("/Test/[action]")]
    public class ValuesController : ControllerBase
    {

        private readonly IMiniProgramApi _service;
        private readonly IBarcode_Service _barservice;
        private readonly INpoi_service _excelservice;
        private readonly IHttpContextAccessor _context;
        private readonly IAnalyzer_jieba _jieba;
        private readonly IEs_knowledge _es_knowledge;

        private readonly IToole_DI _tool;

        private readonly Idiy_menu_service _diymenu_service;

        private readonly IFacePay _face_service;

        private readonly Icustom_service _costom_service;
        private readonly Iwx_media_service _media_service;
        private readonly Iwx_service _iwx_service;
        private readonly IRK_Mqtt _mqtt;

        private readonly Itim_service _tim;

        public ValuesController(IMiniProgramApi Service, IBarcode_Service Barservice, INpoi_service Excelservice, IHttpContextAccessor Context, IAnalyzer_jieba Jieba, IEs_knowledge Es_knowledge, Icustom_service Costom_service, IToole_DI Tool,
             Idiy_menu_service Diymenu_service, IFacePay Face_service,
             Iwx_media_service Media_service, Iwx_service Iwx_service,
              IRK_Mqtt Mqtt, Itim_service Tim
            )
        {
            _service = Service;
            _barservice = Barservice;
            _excelservice = Excelservice;
            _context = Context;
            _jieba = Jieba;
            _es_knowledge = Es_knowledge;
            _costom_service = Costom_service;
            _tool = Tool;
            _diymenu_service = Diymenu_service;
            _face_service = Face_service;
            _media_service = Media_service;
            _iwx_service = Iwx_service;
            _mqtt = Mqtt;
            _tim = Tim;
        }

        [HttpPost]
        public object account_import(account_import_post model)
        {
            return _tim.account_import(model);
        }


        [HttpPost]
        public object account_check(account_check_post model)
        {
            return _tim.account_check(model);
        }



        [HttpPost]
        public object sendmsg(sendmsg_post model)
        {
            return _tim.sendmsg(model);
        }

        [HttpPost]
        public batchsendmsg_result batchsendmsg(batchsendmsg_post model)
        {
            return _tim.batchsendmsg(model);
        }

        [HttpPost]
        public admin_getroammsg_result admin_getroammsg(admin_getroammsg_post model)
        {
            return _tim.admin_getroammsg(model);
        }

        [HttpPost]
        public admin_msgwithdraw_result admin_msgwithdraw(admin_msgwithdraw_post model)
        {
            return _tim.admin_msgwithdraw(model);
        }

        [HttpGet]
        /// <summary>
        /// 
        /// </summary>
        /// <param name="msg_xml"></param>
        /// <returns></returns>
        public string wx_msg(string msg_xml)
        {
            return _iwx_service.wx_msg(msg_xml);
        }
        // GET api/values
        [HttpPost]
        public object Get([FromForm] string content, [FromForm]  string title)
        {
            if (!string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(title))
            {
                //_es_knowledge.Add_Log(new Es_knowledge.knowledge_base
                //{
                //    content = content,
                //    add_time = DateTime.Now,
                //    author = "test",
                //    content_des = content,
                //    hit = 100,
                //    is_rk_private = false,
                //    state = 1,
                //    show_time = DateTime.Now,
                //    title = title,
                //    type_a = "111",
                //    type_b = "222",
                //    type_c = "333",
                //});
            }
            //if (string.IsNullOrWhiteSpace(scene))
            //{
            //    scene = "r=1999";
            //}
            //return _service.get_Unlimited(scene);
            //if (string.IsNullOrWhiteSpace(text))
            //{
            //    return "";
            //}
            //return _jieba.start_cut(text, mode);
            return "";
        }
        [HttpGet]
        public ResultObjModel code2Session(string code)
        {

            return _service.code2Session(code);
        }

        [HttpGet]
        public string GenerateBarCodeBitmap(string code)
        {
            return _barservice.GenerateBarCodeBitmap(code);
        }


        [HttpGet]
        public object getkflist()
        {
            return _costom_service.getkflist();
        }

        [HttpGet]
        public object add(string kf_account, string nickname)
        {
            return _costom_service.add(kf_account, nickname);
        }
        [HttpGet]
        public object inviteworker(string kf_account, string invite_wx)
        {
            return _costom_service.inviteworker(kf_account, invite_wx);
        }

        [HttpGet]
        public object create_session(string kf_account, string openid)
        {
            return _costom_service.create_session(kf_account, openid);
        }

        [HttpGet]
        public object close_session(string kf_account, string openid)
        {
            return _costom_service.close_session(kf_account, openid);
        }

        [HttpGet]
        public object getsessionlist(string kf_account)
        {
            return _costom_service.getsessionlist(kf_account);
        }
        [HttpGet]
        public object getwaitcase()
        {
            return _costom_service.getwaitcase();
        }
        [HttpGet]
        public object send_text(string kf_account, string openid, string content)
        {
            return _costom_service.send_text(kf_account, openid, content);
        }
        [HttpGet]
        public object kf_update(string kf_account, string nickname)
        {
            return _costom_service.kf_update(kf_account, nickname);
        }

        [HttpPost]
        public object uploadheadimg(string kf_account, IFormFileCollection files)
        {
            return _costom_service.uploadheadimg(kf_account, files[0]);
        }
        [HttpGet]
        public object getsession(string openid)
        {
            return _costom_service.getsession(openid);
        }

        [HttpPost]
        public object Mch_Settlement(sub_mch_settlement model)
        {
            return _face_service.Mch_Settlement(model);
        }
        [HttpGet]
        public object get_area()
        {
            return _face_service.get_area;
        }

        [HttpGet]
        public object AlipayTradeQueryRequest(string out_trade_no, string trade_no)
        {
            return _face_service.AlipayTradeQueryRequest(out_trade_no, trade_no);
        }

        [HttpGet]
        public object test_bdc(string datetime)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(datetime))
                {
                    datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
                }
                if (Convert.ToBoolean(datetime.Length & 1))//数字的二进制码最后1位是1则为奇数 
                {
                    datetime = "0" + datetime;//数位为奇数时前面补0 
                }
                Byte[] aryTemp = new Byte[datetime.Length / 2];
                for (int i = 0; i < (datetime.Length / 2); i++)
                {
                    aryTemp[i] = (Byte)(((datetime[i * 2] - '0') << 4) | (datetime[i * 2 + 1] - '0'));
                }
                StringBuilder sb = new StringBuilder();
                for (int index = 0; index < aryTemp.Length; index++)
                {
                    byte b = aryTemp[index];
                    if (b == 0xF)
                    {
                        break;
                    }
                    sb.AppendFormat("{0:d2}", b);
                }
                return sb.ToString();//高位在前 
            }
            catch (Exception ex)
            { return ex.ToString(); }
        }

        [HttpGet]
        public object test_bdc_convert()
        {
            try
            {
                string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
                if (Convert.ToBoolean(datetime.Length & 1))//数字的二进制码最后1位是1则为奇数 
                {
                    datetime = "0" + datetime;//数位为奇数时前面补0 
                }
                Byte[] Bcd = new Byte[datetime.Length / 2];
                for (int i = 0; i < (datetime.Length / 2); i++)
                {
                    Bcd[i] = (Byte)(((datetime[i * 2] - '0') << 4) | (datetime[i * 2 + 1] - '0'));
                }
                var strBcd = Bcd[0].ToString("X2") + Bcd[1].ToString("X2") + "-" + Bcd[2].ToString("X2") + "-" +
                Bcd[3].ToString("X2") + " " + Bcd[4].ToString("X2") + ":" + Bcd[5].ToString("X2") + ":" + Bcd[6].ToString("X2");
                return Convert.ToDateTime(strBcd);
            }
            catch (Exception ex)
            { return ex.ToString(); }
        }

        [HttpGet]
        public string get_fm(string Hex_XOR)
        {
            var ocr = Convert.ToByte(0x83);
            byte y = (byte)~ocr;
            return Hex_XOR + " " + y.ToString("X2");
        }


        #region 微信素材库测试
        [HttpPost]
        public object add_news([FromBody]List<add_news_articles_item> add_list)
        {
            return _media_service.add_news(add_list);
        }

        [HttpPost]
        public object uploadimg(IFormFileCollection files)
        {
            return _media_service.uploadimg(files[0]);
        }
        [HttpPost]
        public object add_material(IFormFileCollection files, string type, string title, string introduction)
        {
            return _media_service.add_material(files[0], type, title, introduction);
        }
        [HttpPost]
        public object batchget_material(string type)
        {
            return _media_service.batchget_material(type, 20, 0);
        }
        [HttpGet]
        public object get_material(string media_id)
        {
            return _media_service.get_material(media_id);
        }
        [HttpGet]
        public object get_materialcount()
        {
            return _media_service.get_materialcount();
        }
        [HttpGet]
        public object del_material(string media_id)
        {
            return _media_service.del_material(media_id);
        }
        [HttpPost]
        public object update_news(update_news_params news_model)
        {
            return _media_service.update_news(news_model);
        }
        #endregion

        [HttpGet]
        public object du_DeviceManage()
        {
            return Http_Helper.HttpPost("http://192.168.3.99:8080/DeviceManage", Newtonsoft.Json.JsonConvert.SerializeObject(new { RequestValue = 2818, pass = "123456" }));
        }
        [HttpPost]
        public object SetRecognitionCallback()
        {
            return Http_Helper.HttpPost("http://192.168.3.99:8080/DeviceManage", Newtonsoft.Json.JsonConvert.SerializeObject(new { RequestValue = 2828, pass = "123456", callback_url= "http://192.168.3.10:1958/Test/RecognitionCallback" }));
        }
        [HttpPost]
        public object RecognitionCallback(RecognitionCallback_item Params) { 
            _tool.di_es.Add_Log(Newtonsoft.Json.JsonConvert.SerializeObject(Params), "du_test");
            Base64ToImage(Params.image, "C://du_test/", _tool.di_getid.IGet_SnowFlake_Id);
            return "success";
        }



        [HttpPost]
        public object In_user(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                return "fail";
            }
            return Http_Helper.HttpPost("http://192.168.3.99:8080/UserManage", Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                RequestValue = 2817,
                pass = "123456",
                image_content = ImageToBase64(url),
                image_type = "image",
                user_id = _tool.di_getid.IGet_SnowFlake_Id,
                quality_control = "NONE",
                user_info = new
                {
                    name = "test_"+ _tool.di_getid.IGet_SnowFlake_Id
                }
            }));
        }


        private string Base64ToImage(string base64Str, string path, string imgName)
        {
            string filename = "";//声明一个string类型的相对路径
            //取图片的后缀格式
            //string hz = base64Str.Split(',')[0].Split(';')[0].Split('/')[1];
            string[] str = base64Str.Split(',');  //base64Str为base64完整的字符串，先处理一下得到我们所需要的字符串
            byte[] imageBytes = Convert.FromBase64String(base64Str);
            //读入MemoryStream对象
            MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
            memoryStream.Write(imageBytes, 0, imageBytes.Length);
            filename = path + imgName + ".jpg";//所要保存的相对路径及名字
            string tmpRootDir = path; //获取程序根目录 
            if (!Directory.Exists(tmpRootDir))
            {
                Directory.CreateDirectory(tmpRootDir);
            }
            string imagesurl2 = tmpRootDir + imgName + ".jpg"; //转换成绝对路径 
            //  转成图片
            Image image = Image.FromStream(memoryStream);
            //   图片名称
            string iname = DateTime.Now.ToString("yyMMddhhmmss");
            image.Save(imagesurl2);  // 将图片存到本地Server.MapPath("pic\\") + iname + "." + hz
            return filename;
        }

        /// <summary>
        /// Image 转成 base64
        /// </summary>
        /// <param name="fileFullName"></param>
        private string ImageToBase64(string fileFullName)
        {
            Bitmap bmp = null;
            try
            {
                var suffix = Path.GetExtension(fileFullName).ToLower();
                var suffixName = suffix == ".png" ? ImageFormat.Png
                    : suffix == ".jpg" || suffix == ".jpeg"
                        ? ImageFormat.Jpeg
                        : suffix == ".bmp"
                            ? ImageFormat.Bmp
                            : suffix == ".gif"
                                ? ImageFormat.Gif
                                : ImageFormat.Jpeg;

                string result = string.Empty;
                bmp = new Bitmap(fileFullName);
                using (MemoryStream ms = new MemoryStream())
                {
                    bmp.Save(ms, suffixName);
                    byte[] arr = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();
                    result = Convert.ToBase64String(arr);
                }
                return result;
            }
            catch (Exception ex)
            { 
                return null;
            }
            finally
            {
                if (bmp != null)
                    bmp.Dispose();
            }
        }
        public class RecognitionCallback_item
        {
            public string device_id { get; set; }

            public float score { get; set; }

            public long timestamp { get; set; }

            public string user_id { get; set; }

            public string username { get; set; }

            public string image { get; set; }
        }
    }
}
